/*
Package mail
@Author   : Uyynot
@Email    : uyynot@qq.com
@Time     : 2024/2/26 16:00
@File     : mail.go
@Project  : gohub
@Desc     :
*/
package mail

import (
	"gohub/pkg/config"
	"sync"
)

func init() {
	config.Add("mail", func() map[string]any {
		return map[string]any{
			//默认Mailhog的配置
			"smtp": map[string]any{
				"host":     config.Env("MAIL_HOST", "localhost"),
				"port":     config.Env("MAIL_PORT", 1025),
				"username": config.Env("MAIL_USERNAME", ""),
				"password": config.Env("MAIL_PASSWORD", ""),
			},
			"from": map[string]any{
				"address": config.Env("MAIL_FROM_ADDRESS", "uyynot@mail.com"),
				"name":    config.Env("MAIL_FROM_NAME", "Gohub"),
			},
		}
	})
}

type From struct {
	Address string
	Name    string
}

type Email struct {
	From    From
	To      []string // 收件人
	Bcc     []string // 秘密抄送
	Cc      []string // 抄送
	Subject string   // 主题
	Text    []byte   // Plaintext message (optional)
	HTML    []byte   // Html message (optional)
}

type Mailer struct {
	Driver Driver
}

var once sync.Once
var internalMailer *Mailer

// NewMailer 单例模式获取
func NewMailer() *Mailer {
	once.Do(func() {
		internalMailer = &Mailer{
			Driver: &SMTP{},
		}
	})
	return internalMailer
}

func (mailer *Mailer) Send(email Email) bool {
	return mailer.Driver.Send(email, config.GetStringMapString("mail.smtp"))
}
